﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using ERP_RORZE_SYSTEM;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_RORZE_DLL.Business
{
    public partial class frm_Add_MasterPO : Form
    {
        private INISettings mySetting;
        private SqlConnection myConnection;
        private string newPOID;

        public frm_Add_MasterPO()
        {
            InitializeComponent();
            this.mySetting = new INISettings();
            this.myConnection = new SqlConnection(mySetting.SQLConnectionString);
            this.newPOID = null;
            this.inputDate.EditValue = DateTime.Now;
            InitialPOID();            
            getSupplierList();
            this.supplierID.Properties.AutoComplete = true;            
            this.commodityName.Text = "Parts for RORZE ROBOTECH CO., LTD.";
            getDeliveryList();
            this.deliveryID.Properties.AutoComplete = true;            
            getShipToList();
            this.shiptoID.Properties.AutoComplete = true;            
            getPaymentList();
            this.paymentID.Properties.AutoComplete = true;            
            getTransportList();
            this.transportID.Properties.AutoComplete = true;

            this.inputDate.DateTimeChanged += inputDate_DateTimeChanged;
        }

        void inputDate_DateTimeChanged(object sender, EventArgs e)
        {            
            InitialPOID();
        }

        ////////////////////////////////////////////////
        /// Initial new PO information to form
        ////////////////////////////////////////////////        
        private void InitialPOID()
        {
            if (this.inputDate.EditValue != null)
            {
                int current_year = this.inputDate.DateTime.Year % 100;
                int new_id_number = 0;
                string new_id_string = "";
                try
                {
                    myConnection.Open();
                    SqlCommand cmd_sql = myConnection.CreateCommand();
                    cmd_sql.CommandText = "SELECT MAX(SUBSTRING(ID, 12, 4))"
                        + " FROM [241_MasterPO] WHERE SUBSTRING(ID, 5, 2) = '" + current_year.ToString() + "'";
                    SqlDataReader dataReader = cmd_sql.ExecuteReader();
                    if (dataReader.Read())
                    {
                        if (dataReader[0] != DBNull.Value)
                        {
                            new_id_number = Int32.Parse(dataReader[0].ToString());
                        }
                    }
                    new_id_number++;
                    dataReader.Close();
                    cmd_sql.Dispose();
                    myConnection.Close();
                    DateTime in_Date = this.inputDate.DateTime;
                    new_id_string = in_Date.Year.ToString().Substring(2) + in_Date.Month.ToString("D2") + in_Date.Day.ToString("D2");
                    new_id_string = "/" + new_id_string + "/" + new_id_number.ToString("D4") + "-00F";
                }
                catch
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    MessageBox.Show("Cannot create new PO ID");
                    this.Dispose();
                }
                this.poNo.Text = new_id_string;
            }
            else
            {
                this.poNo.Text = "";
            }
        }
        
        ////////////////////////////////////////////////
        /// Load Supplier list to form
        ////////////////////////////////////////////////
        private void getSupplierList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT SupplierID, SupplierName FROM [222_Supplier] ORDER BY SupplierName";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["SupplierName"].ToString();
                    item.Value = dataReader["SupplierID"].ToString();
                    this.supplierID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get Supplier list");
            }
        }

        ////////////////////////////////////////////////
        /// Load Delivery list to form
        ////////////////////////////////////////////////
        private void getDeliveryList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT DeliveryTermID, DeliveryTermName FROM [222_DeliveryTerm] ORDER BY DeliveryTermName";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["DeliveryTermName"].ToString();
                    item.Value = dataReader["DeliveryTermID"].ToString();
                    this.deliveryID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get Delivery list");
            }
        }

        ////////////////////////////////////////////////
        /// Load Ship To list to form
        ////////////////////////////////////////////////
        private void getShipToList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT ShipToCode, ShipToName FROM [222_ShipTo] ORDER BY ShipToName";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["ShipToName"].ToString();
                    item.Value = dataReader["ShipToCode"].ToString();
                    this.shiptoID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get Ship To list");
            }
        }

        ////////////////////////////////////////////////
        /// Load Payment list to form
        ////////////////////////////////////////////////
        private void getPaymentList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT PaymentID, PaymentName FROM [222_Payment] ORDER BY PaymentName";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["PaymentName"].ToString();
                    item.Value = dataReader["PaymentID"].ToString();
                    this.paymentID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get Payment list");
            }
        }

        ////////////////////////////////////////////////
        /// Load Transport List to form
        ////////////////////////////////////////////////
        private void getTransportList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT TransportID, TransportName FROM [222_Transport] ORDER BY TransportName";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["TransportName"].ToString();
                    item.Value = dataReader["TransportID"].ToString();
                    this.transportID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get Transport list");
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            string error = null;

            DateTime inputdate = new DateTime();
            string supplier = null;
            string delivery = null;
            string payment = null;
            string shipto = null;
            string transport = null;

            ComboboxItem item = new ComboboxItem();

            if (this.inputDate.EditValue == null)
            {
                error = "Please select input date";
            }
            else
            {
                DateTime.TryParse(this.inputDate.EditValue.ToString(), out inputdate);
            }

            if (string.IsNullOrEmpty(error))
            {
                if (string.IsNullOrEmpty(this.prefixID.Text))
                {
                    error = "Please select Supplier";
                }
                else
                {
                    this.newPOID = this.prefixID.Text + this.poNo.Text;
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (this.supplierID.SelectedIndex < 0)
                {
                    error = "Please select Supplier";
                }
                else
                {
                    item = (ComboboxItem)this.supplierID.SelectedItem;
                    supplier = item.Value.ToString();
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (this.deliveryID.SelectedIndex < 0)
                {
                    delivery = "NF";
                }
                else
                {
                    item = (ComboboxItem)this.deliveryID.SelectedItem;
                    delivery = item.Value.ToString();
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (this.shiptoID.SelectedIndex < 0)
                {
                    error = "Please select Ship To";
                }
                else
                {
                    item = (ComboboxItem)this.shiptoID.SelectedItem;
                    shipto = item.Value.ToString();
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (this.paymentID.SelectedIndex < 0)
                {
                    error = "Please select Payment";
                }
                else
                {
                    item = (ComboboxItem)this.paymentID.SelectedItem;
                    payment = item.Value.ToString();
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (this.transportID.SelectedIndex < 0)
                {
                    error = "Please select Transport";
                }
                else
                {
                    item = (ComboboxItem)this.transportID.SelectedItem;
                    transport = item.Value.ToString();
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                try
                {                    
                    myConnection.Open();
                    string sql = "INSERT INTO [241_MasterPO]"
                        + " (ID, InputDate, SupplierID, NameOfCommodity, DeliveryTermID, PaymentID, TransportID, Remark, ShipToCode)"
                        + " VALUES ('" + newPOID + "', @inputdate, '" + supplier + "', '" + commodityName.Text + "',"
                        + " '" + delivery + "', '" + payment + "', '" + transport + "', '" + remarkText.Text + "', '" + shipto + "')";
                    SqlCommand cmd_sql = new SqlCommand(sql, myConnection);
                    cmd_sql.Parameters.Add("@inputdate", SqlDbType.DateTime).Value = inputdate.Date;
                    cmd_sql.ExecuteNonQuery();
                    cmd_sql.Dispose();
                    myConnection.Close();
                    MessageBox.Show("Master PO added success!");
                    //this.Dispose();
                    clearForm();
                }
                catch //(Exception ex)
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    MessageBox.Show("Cannot add Master PO. Plase try again.");
                    //MessageBox.Show(ex.Message);
                }
            }
            else
            {
                MessageBox.Show(error);
            }
        }

        private void clearForm()
        {
            foreach (Control c in this.Controls)
            {
                if (c is DevExpress.XtraEditors.TextEdit)
                {
                    ((DevExpress.XtraEditors.TextEdit)c).Text = null;
                }

                if (c is DevExpress.XtraEditors.ComboBoxEdit)
                {
                    ((DevExpress.XtraEditors.ComboBoxEdit)c).SelectedIndex = -1;
                }

                if (c is System.Windows.Forms.MaskedTextBox)
                {
                    ((System.Windows.Forms.MaskedTextBox)c).Text = null;
                }
            }
        }

        //////////////////////
        /// Supplier Change
        //////////////////////
        private void supplierID_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.supplierID.SelectedIndex >= 0)
            {
                ComboboxItem item = (ComboboxItem)this.supplierID.SelectedItem;
                try
                {
                    myConnection.Open();
                    SqlCommand cmd_sql = myConnection.CreateCommand();
                    cmd_sql.CommandText = "SELECT [SupplierID_PO], [NameOfCommodity]"
                        + " FROM [222_Supplier] WHERE [SupplierID]='" + item.Value.ToString() + "'";
                    SqlDataReader dataReader = cmd_sql.ExecuteReader();
                    if (dataReader.Read())
                    {
                        this.prefixID.Text = dataReader["SupplierID_PO"].ToString();
                        //this.commodityName.Text = dataReader["NameOfCommodity"].ToString();
                    }
                    else
                    {
                        this.prefixID.Text = null;
                        this.commodityName.Text = null;
                    }
                    dataReader.Close();
                    cmd_sql.Dispose();
                    myConnection.Close();
                }
                catch
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    MessageBox.Show("Cannot get SupplierID PO");
                }
            }
        }
    }   
}
